const axios = require('axios');
const config = require('./config');

class GitLabAPI {
  constructor() {
    this.api = axios.create({
      baseURL: `${config.gitlab.baseUrl}/api/v4`,
      headers: {
        'PRIVATE-TOKEN': config.gitlab.accessToken
      }
    });
  }

  async getProjects() {
    try {
      const allProjects = [];
      let page = 1;
      const perPage = 100;
      
      while (true) {
        const response = await this.api.get('/projects', {
          params: {
            page,
            per_page: perPage
          }
        });
        
        const projects = response.data;
        allProjects.push(...projects);
        
        if (projects.length < perPage) {
          break;
        }
        
        page++;
      }
      
      return allProjects;
    } catch (error) {
      console.error('获取项目列表失败:', error.message);
      throw error;
    }
  }

  async getProjectBranches(projectId) {
    try {
      const allBranches = [];
      let page = 1;
      const perPage = 100;
      
      while (true) {
        const response = await this.api.get(`/projects/${projectId}/repository/branches`, {
          params: {
            page,
            per_page: perPage
          }
        });
        
        const branches = response.data;
        allBranches.push(...branches);
        
        if (branches.length < perPage) {
          break;
        }
        
        page++;
      }
      
      return allBranches;
    } catch (error) {
      console.error(`获取项目 ${projectId} 的分支列表失败:`, error.message);
      throw error;
    }
  }
}

module.exports = new GitLabAPI();
